import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { VideoGroup } from './video-group.entity';

@Injectable()
export class VideoGroupService {
    constructor(
        @InjectRepository(VideoGroup)
        private videoGroupRepository: Repository<VideoGroup>,
    ) { }

    // 创建视频组
    async create(videoGroup: VideoGroup): Promise<VideoGroup> {
        return this.videoGroupRepository.save(videoGroup);
    }

    // 根据 ID 查询视频组
    async findOne(id: number): Promise<VideoGroup> {
        const videoGroup = await this.videoGroupRepository.findOne({ where: { id } });
        if (!videoGroup) {
            throw new NotFoundException(`Video group with id ${id} not found`);
        }
        return videoGroup;
    }

    // 模糊查询视频组
    async findByGroupName(groupName: string): Promise<VideoGroup[]> {
        return this.videoGroupRepository
            .createQueryBuilder('videoGroup')
            .where('videoGroup.groupName LIKE :groupName', { groupName: `%${groupName}%` })
            .getMany();
    }

    // 获取所有视频组
    async findAll(): Promise<VideoGroup[]> {
        return this.videoGroupRepository.find();
    }

    // 更新视频组
    async update(id: number, videoGroup: VideoGroup): Promise<VideoGroup> {
        await this.videoGroupRepository.update(id, videoGroup);
        return this.findOne(id);
    }

    // 批量删除视频组
    async removeMultiple(ids: number[]): Promise<void> {
        const result = await this.videoGroupRepository.delete(ids);
        if (result.affected === 0) {
            throw new NotFoundException(`Video groups with ids ${ids.join(', ')} not found`);
        }
    }

    // 分页和模糊查询视频组
    async findAllWithPaginationAndSearch(
        pageSize: number,
        currentPage: number,
        groupName?: string,
    ): Promise<{ data: VideoGroup[]; total: number }> {
        const queryBuilder = this.videoGroupRepository.createQueryBuilder('videoGroup');

        if (groupName) {
            queryBuilder.where('videoGroup.groupName LIKE :groupName', { groupName: `%${groupName}%` });
        }

        // 按创建时间降序排列
        queryBuilder.orderBy('videoGroup.createTime', 'DESC');

        const total = await queryBuilder.getCount();
        const data = await queryBuilder
            .skip((currentPage - 1) * pageSize)
            .take(pageSize)
            .getMany();

        return { data, total };
    }
}